import { WebSocketServer } from 'ws';
import { createServer } from 'http';
import { URL } from 'url';

// 创建 HTTP 服务器
const server = createServer();

// 创建 WebSocket 服务器
const wss = new WebSocketServer({ 
  server,
  path: '/uam/v2/ws/uam/channel/245'
});

console.log('WebSocket 服务器启动中...');

// 模拟飞机轨迹数据
class AircraftTracker {
  constructor() {
    this.aircrafts = new Map();
    this.initializeAircrafts();
  }

  initializeAircrafts() {
    // 初始化多架飞机
    const aircrafts = [
      {
        id: 'AC001',
        name: '航班001',
        startLon: 116.4074, // 北京
        startLat: 39.9042,
        startAlt: 10000,
        heading: 135, // 东南方向
        speed: 800
      },
      {
        id: 'AC002',
        name: '航班002',
        startLon: 121.4737, // 上海
        startLat: 31.2304,
        startAlt: 12000,
        heading: 315, // 西北方向
        speed: 750
      },
      {
        id: 'AC003',
        name: '航班003',
        startLon: 113.2644, // 广州
        startLat: 23.1291,
        startAlt: 9000,
        heading: 45, // 东北方向
        speed: 850
      }
    ];

    aircrafts.forEach(aircraft => {
      this.aircrafts.set(aircraft.id, {
        ...aircraft,
        currentLon: aircraft.startLon,
        currentLat: aircraft.startLat,
        currentAlt: aircraft.startAlt,
        trackPoints: []
      });
    });
  }

  updateAircraftPositions() {
    this.aircrafts.forEach((aircraft, id) => {
      // 根据航向角和速度更新位置
      const headingRad = aircraft.heading * Math.PI / 180;
      const distance = aircraft.speed / 3600; // 每秒移动距离
      
      // 更新经纬度
      aircraft.currentLon += Math.cos(headingRad) * distance * 0.01;
      aircraft.currentLat += Math.sin(headingRad) * distance * 0.01;
      
      // 随机高度变化
      aircraft.currentAlt += (Math.random() - 0.5) * 200;
      
      // 确保高度在合理范围内
      aircraft.currentAlt = Math.max(8000, Math.min(15000, aircraft.currentAlt));
      
      // 添加轨迹点
      aircraft.trackPoints.push({
        timestamp: new Date().toISOString(),
        longitude: aircraft.currentLon,
        latitude: aircraft.currentLat,
        altitude: aircraft.currentAlt,
        heading: aircraft.heading,
        speed: aircraft.speed
      });
      
      // 限制轨迹点数量
      if (aircraft.trackPoints.length > 50) {
        aircraft.trackPoints.shift();
      }
    });
  }

  getAllAircraftsData() {
    const data = [];
    this.aircrafts.forEach((aircraft, id) => {
      data.push({
        aircraftId: aircraft.id,
        name: aircraft.name,
        timestamp: new Date().toISOString(),
        longitude: aircraft.currentLon,
        latitude: aircraft.currentLat,
        altitude: aircraft.currentAlt,
        heading: aircraft.heading,
        speed: aircraft.speed,
        trackPoints: aircraft.trackPoints
      });
    });
    return data;
  }
}

const tracker = new AircraftTracker();

// WebSocket 连接处理
wss.on('connection', (ws, req) => {
  console.log(`新的 WebSocket 连接: ${req.socket.remoteAddress}`);
  console.log(`请求路径: ${req.url}`);
  
  // 发送初始数据
  const initialData = {
    type: 'init',
    aircrafts: tracker.getAllAircraftsData()
  };
  ws.send(JSON.stringify(initialData));
  
  // 设置定时器发送实时数据
  const interval = setInterval(() => {
    if (ws.readyState === 1) { // WebSocket.OPEN
      tracker.updateAircraftPositions();
      
      const updateData = {
        type: 'update',
        aircrafts: tracker.getAllAircraftsData()
      };
      
      ws.send(JSON.stringify(updateData));
    } else {
      clearInterval(interval);
    }
  }, 1000); // 每秒更新一次
  
  // 连接关闭处理
  ws.on('close', () => {
    console.log('WebSocket 连接已关闭');
    clearInterval(interval);
  });
  
  // 错误处理
  ws.on('error', (error) => {
    console.error('WebSocket 错误:', error);
    clearInterval(interval);
  });
});

// 启动服务器
const PORT = process.env.PORT || 6088;
server.listen(PORT, () => {
  console.log(`WebSocket 服务器运行在端口 ${PORT}`);
  console.log(`WebSocket URL: ws://127.0.0.1:${PORT}/uam/v2/ws/uam/channel/245`);
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('正在关闭服务器...');
  server.close(() => {
    console.log('服务器已关闭');
    process.exit(0);
  });
});
